package com.wu.client.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.wu.client.cache.newData.NewAlbumCache;
import com.wu.client.cache.newData.NewSongCache;
import com.wu.client.constant.ResTypeEnum;
import com.wu.client.dao.redis.Likes;
import com.wu.client.dto.AlbumMongo;
import com.wu.client.dto.SongMongo;
import com.wu.client.service.NewService;
import com.wu.client.service.UserLikesService;
import com.wu.client.utils.PageRespUtil;
import com.wu.client.vo.res.PageResp;
import com.wu.client.vo.res.album.AlbumBaseResp;
import com.wu.client.vo.res.song.SongBaseResp;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author Cousin
 * @date 2025/3/28
 * @Description
 */
@Service
@RequiredArgsConstructor
public class NewServiceImpl implements NewService {
    private final UserLikesService userLikesService;
    @Override
    public PageResp<AlbumBaseResp> getNewAlbums(Integer page, Integer limit) {
        NewAlbumCache newAlbumCache = NewAlbumCache.getInstance();
        List<AlbumMongo> albumMongoList = newAlbumCache.getInPage(page, limit);
        if (CollectionUtil.isNotEmpty(albumMongoList)){
            List<AlbumBaseResp> albumBaseRespList = BeanUtil.copyToList(albumMongoList, AlbumBaseResp.class);
            long total = newAlbumCache.getTotal();
            return PageRespUtil.buildPageResp(page,limit,total,albumBaseRespList);
        }
        return new PageResp<>();
    }

    @Override
    public PageResp<SongBaseResp> getNewSongs(Long userId, Integer page, Integer limit) {
        NewSongCache newSongCache = NewSongCache.getInstance();
        List<SongMongo> songMongoList = newSongCache.getInPage(page, limit);
        if (CollectionUtil.isNotEmpty(songMongoList)){
            List<SongBaseResp> songBaseRespList = BeanUtil.copyToList(songMongoList, SongBaseResp.class);
            List<Long> songIds = songBaseRespList.stream().map(SongBaseResp::getId).toList();
            Map<Long, Likes> songLikesMap = userLikesService.checkUserIfLike(ResTypeEnum.SONG, userId, songIds);
            for (SongBaseResp songBaseResp : songBaseRespList) {
                Likes likes = songLikesMap.get(songBaseResp.getId());
                if (ObjectUtil.isNotNull(likes)){
                    songBaseResp.setIsLiked(likes.getIsLiked());
                }
            }
            long total = newSongCache.getTotal();
            return PageRespUtil.buildPageResp(page,limit,total,songBaseRespList);
        }
        return new PageResp<>();
    }
}
